<?php


namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Linkslists;
use App\Models\Linksrecord;
use App\Models\Linksliststhird;
use App\Models\Linkslistsqrcodes;
use App\Models\Linkslistssetting;
use App\Services\IpService;
use App\Services\OutputService;
use App\Services\CacheService;
use App\Services\DeviceService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Log;

class StatisticsController extends Controller
{
    public function linksApi(Request $request,$version)
    {
        // 老的手动上架的小程序调用本接口
        $linkParamas = explode("_",$request->links_id);
        $links_id = $linkParamas[0];
        $sign = md5($request->time."ttwl88".$request->links_id);
        if ($sign != $request->sign) return response()->json(['status' => "error", 'code' => "1001", 'msg' => "请求异常,请重新加载！", 'data' => []]);
        if(Cache::has('links_api_'.$links_id)) {
            $links = Cache::get('links_api_'.$links_id);
        } else {
            $links = Linkslists::jumpGetApiLinks($links_id);
            if (empty($links)) return OutputService::error("您访问的链接不存在！");
            if ($links->disable != 1) return OutputService::error("链接已删除！");
            if ($links->limit_status == 1 && $links->left_pv <= 0) return OutputService::error("链接访问次数不足,请充值！");
            if ($links->limit_pv > 1000 && $links->end_time < time()) return OutputService::error("会员已过期,请续费后访问充值！");
            if ($links->limit_pv < 1000 && $links->end_time < time()) return OutputService::error("免费体验已过期1小时,请开通会员后访问！");
            if ($links->platfrom_type == 6) {
                $third = Linksliststhird::getLinksListsThird($links_id);
                $links->msg = json_encode(["mini_id"=>$third->appid,"path"=>$third->path,"original_id"=>$third->original_id]);
            }
            // 获取小程序内样式
            $linksSetting = Linkslistssetting::getLinksListsSetting($links_id);
            $links = collect($links)->merge($linksSetting)->all();

            // 每次调用缓存30分钟
            Cache::put('links_api_'.$links_id, $links, 1800);
        }

        if (in_array($links["platfrom_type"], [8,9,11,12])) {
            $batch = date("Ymd");
            $qrcodes = Redis::hget("links_qrcodes_".$batch, $links_id);
            if (empty($qrcodes)) {
                // 更新昨天二维码数据并且删除缓存
                CacheService::removeLinksQrcodeCache($links_id,date("Ymd",strtotime("-1 day")));
                $qrcodes = Linkslistsqrcodes::getAllLinksListsQrcodes($links_id);
                if (empty($qrcodes)) return OutputService::error("当前暂无可用二维码！");
                Redis::hset("links_qrcodes_".$batch, $links_id, json_encode($qrcodes));
            } else {
                $qrcodes = json_decode($qrcodes);
            }
            if (empty($qrcodes)) return OutputService::error("当前暂无可用二维码！");
            $qrcode_image = "";
            if ($links["qrcode_switch"] == 2){
                // 随机二维码
                try {
                    $qrcodeCount = count($qrcodes);
                } catch (Exception $e) {
                    $qrcodeCount = count($qrcodes->toArray());
                }
                // 随机二维码
                if ($qrcodeCount >= 0) {
                    $key = rand(0,$qrcodeCount-1);
                } else {
                    $key = 0;
                }
                $qrcodes[$key]->scan_total += 1;
                $qrcodes[$key]->scan_today += 1;
                $qrcode_image = $qrcodes[$key]->img_url;
            } else {
                $qrcodes = collect($qrcodes);
                if ($links["qrcode_switch"] == 1) {
                    // 顺序切换
                    $qrcodes = $qrcodes->sortByDesc('rate')->all();
                } else {
                    // 循环切换
                    $qrcodes = $qrcodes->sortBy('scan_today')->all();
                }
                foreach ($qrcodes as $key => $qrcode) {
                    if ($links["qrcode_upper"] == 1) {
                        // 累计上限
                        if ($qrcode->scan_total < $qrcode->count_limit) {
                            $qrcodes[$key]->scan_total += 1;
                            $qrcodes[$key]->scan_today += 1;
                            $qrcode_image = $qrcode->img_url;
                            break;
                        }
                    } else {
                        // 每日上限
                        if ($qrcode->scan_today < $links["qrcode_daily"]) {
                            $qrcodes[$key]->scan_total += 1;
                            $qrcodes[$key]->scan_today += 1;
                            $qrcode_image = $qrcode->img_url;
                            break;
                        }
                    }
                }
            }
            if (empty($qrcode_image)) return OutputService::error("当前暂无二维码,请查看二维码设置的二维码有效期和访问上限！");
            Redis::hset("links_qrcodes_".$batch, $links_id, json_encode($qrcodes));
            if ($version >= 3){
                $links["msg"] = $qrcode_image;
            } else {
                $links["msg"] = json_encode([$qrcode_image]);
            }
        }

        if ($version >= 3) return OutputService::success("Success",$links);

        //公众号二维码模式兼容以前上架的小程序
        $platfrom_type = $links["platfrom_type"] == 12 ? 11 : $links["platfrom_type"];
        if ($version <= 1) {
            // 摩尔活码
            if ($links["platfrom_type"] == 13) {
                $platfrom_type = 1;
            }
        }
        $describe_show = in_array($links["platfrom_type"],[2,3,6]) ? $links["button_show"] : $links["miniapp_style"];
        $describe = in_array($links["platfrom_type"],[2,3,6]) ? $links["button_text"] : $links["describe"];
        $data = ["title"=>"","nike"=>$links["nike"],"platfrom_type"=>$platfrom_type,"describe"=>$describe,"type"=>$links["type"],"msg"=>$links["msg"],"status"=>1,"links_id"=>$links["links_id"],"image"=>$links["logo"],"notice"=>$links["button_text"],"describe_show"=>$describe_show,"notice_img"=>$links["logo"],"wechat"=>"","text"=>$links["qrcode_notice"],"image_notice"=>""];
        return OutputService::success("Success",$data);
    }

    public function linkStatic(Request $request)
    {
        // 7月5日前老版本数据统计(手动上架)
        if (empty($request->links_id) || $request->links_id == "undefined") return OutputService::error("Error");
        // 判断是否有CDN
        $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
        // 小程序端调用
        $linkParamas = explode("_", $request->links_id);
        $links_id = $linkParamas[0];
        $record_id = isset($linkParamas[1]) ? $linkParamas[1] : "";

        $today = date("Ymd",time());
        if (empty($record_id)) {
            $linkRecord = new Linksrecord();
        } else {
            $linkRecord = new Linksrecord(["tbnum"=>$record_id[0]]);
        }
        
        if (empty($record_id)) {
            // 小程序直接拉起
            $record_id = (date("m",time())%4).substr(md5($ip),0,31);
            if ($request->active == 1) {
                // active:1.展示二维码回调2.长按识别回调
                $system = DeviceService::getSystem($request->vendor);
                $device = DeviceService::getDevices($request->pvendor);

                // 根据IP获取城市信息
                $ipinfo = IpService::getAddressByIp($ip);
                $province = mb_substr($ipinfo["province"], 0, 9);
                $city = mb_substr($ipinfo["city"], 0, 14);
                // 增加直接跳转访问PV
                Redis::hincrby('mini_direct_'.$today,$links_id,1);
                $mini_show_time = time();
                $mini_open_time = $mini_show_time-1;
                // 创建小程序访问记录
                $linkRecord->creatLinkRecordMini($record_id,$links_id,$province,$city,$system,$device,1,$ip,"",$mini_open_time,$mini_show_time,1,1,1);
            } else {
                Redis::hincrby('mini_activate_'.$today,$links_id,1);
                // 更新小程序长按识别
                $linkRecord->updateLinkRecordPressTime($record_id,time());
            }
        } else {
            if ($request->active == 1) {
                $mini_show_time = time();
                $mini_open_time = $mini_show_time-1;
                // 更新二维码展示时间
                $linkRecord->updateLinkRecordShowTime($record_id,$mini_show_time,$mini_open_time);
                Redis::hincrby('mini_view_'.date("Ymd",time()), $links_id, 1);
            } else {
                Redis::hincrby('mini_activate_'.$today,$links_id,1);
                // 更新小程序长按识别
                $linkRecord->updateLinkRecordPressTime($record_id,time());
            }
        }
        return OutputService::success("SUCCESS");
    }
}